package cn.bobohost.crmrbac.web.controller;

import cn.bobohost.crmrbac.pojo.po.Department;
import cn.bobohost.crmrbac.pojo.po.Employee;
import cn.bobohost.crmrbac.pojo.po.Role;
import cn.bobohost.crmrbac.pojo.query.EmployeeQuery;
import cn.bobohost.crmrbac.service.DepartmentService;
import cn.bobohost.crmrbac.service.EmployeeService;
import cn.bobohost.crmrbac.service.RoleService;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 波波老师
 * @since 2025-05-21
 */
@Controller
@RequestMapping("/employee")
@RequiredArgsConstructor
@Slf4j
public class EmployeeController {

    //注入员工service
    private final EmployeeService employeeService;
    //注入部门service
    private final DepartmentService departmentService;
    
    //注入角色service
    private final RoleService roleService;

    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") EmployeeQuery  employeeQuery){

        log.debug("员工条件查询对象：{}",employeeQuery);

        //1. 填充页面的部门下拉列表
        List<Department> departmentList = departmentService.findDepartmentList();
        model.addAttribute("departments",departmentList);

        //2. 查询分页列表
        //调用业务层
        PageInfo<Employee> pageInfo = employeeService.findEmployeeListPage(employeeQuery);
        //将分页数据放入模型对象中
        model.addAttribute("pageInfo",pageInfo);


        //重定向到模版页面，进行填充
        return "employee/list";

    }

    /**
     * 显示修改页面
     * @param model
     * @param id
     * @return
     */
    @RequestMapping("/input")
//    public String intput(Model model,Long id){
    public String intput(Model model,@RequestParam(value="id",required = false) Long id){
        //判断id是否存在，如果存在，则根据id查询数据填充表单--修改
        if(null != id){
            //根据id查询数据
            Employee employee = employeeService.getById(id);

            //填充员工拥有的角色
            List<Role> empRoleList=roleService.findListByEmploeeId(employee.getId());

            employee.setRoles(empRoleList);

            model.addAttribute("employee",employee);
        }

        //查询所有部门列表
        List<Department> departmentList = departmentService.list();
        model.addAttribute("departments", departmentList);
        
        
        //填充所有角色
        List<Role> roleList = roleService.list();
        model.addAttribute("roles",roleList);

        //重定向到员工表单页面
        return "employee/input";
    }

}
